﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dln.Model;
using Dln.Common.Helper;
using Dln.Handler;
using Dln.Common.WxPayAPI;

namespace Handler.Business
{
    public class WeChatUsersBusiness
    {
        public static bool IsExistOpenId(string openId)
        {
            var uptModel = SqlHelper.Context.From<WeChatUsers>().Where(d => d.Openid == openId);
            if (uptModel != null && uptModel.Count() > 0)
            {
                var weChatUsersModel = uptModel.ToFirstDefault();

                var userInfoModel = WeChatSdk.GetUserInfo(openId);

                if (userInfoModel == null) return true;
                weChatUsersModel.AddTime = DateTime.Now;
                weChatUsersModel.Openid = userInfoModel.openid;
                weChatUsersModel.Sex = userInfoModel.sex;
                weChatUsersModel.Nickname = userInfoModel.nickname;
                weChatUsersModel.Headimgurl = userInfoModel.headimgurl;
                var count1 = SqlHelper.Context.Update<WeChatUsers>(weChatUsersModel);

                return true;
            }
            else
            {
                return false;
            }
        }

        public static void Insert(string OpenId)
        {
            var UserInfoModel = WeChatSdk.GetUserInfo(OpenId);
            if (UserInfoModel == null)
            {
                Log.Info("WxPayApi", "Report request : " + "获取微信信息失败");
            }
            if (UserInfoModel != null)
            {
                var weChatUsersModel = new WeChatUsers();
                weChatUsersModel.AddTime = DateTime.Now;
                weChatUsersModel.Openid = UserInfoModel.openid;
                weChatUsersModel.Sex = UserInfoModel.sex;
                weChatUsersModel.Nickname = UserInfoModel.nickname;
                weChatUsersModel.Headimgurl = UserInfoModel.headimgurl;
                var count1 = SqlHelper.Context.Insert<WeChatUsers>(weChatUsersModel);
            }
        }
    }
}
